from django import template
from django.db.models import Count, Q
from story.models import Story
from interactive.models import Like, Favorite, Comment

register = template.Library()

@register.filter
def is_liked_by_user(story, user):
    """Check if a story is liked by the given user"""
    if not user.is_authenticated:
        return False
    return Like.objects.filter(story=story, user=user).exists()

@register.filter
def get_likes_count(story):
    """Get the number of likes for a story"""
    return Like.objects.filter(story=story).count()

@register.filter
def is_favorited_by_user(favorites, user):
    """Check if a story is favorited by the given user"""
    if not user.is_authenticated:
        return False
    for favorite in favorites:
        if favorite.user == user:
            return True
    return False

@register.filter
def get_comments_count(story):
    """Get the number of comments for a story"""
    return Comment.objects.filter(story=story, parent=None).count()

@register.simple_tag
def get_stories_by_category(category, limit=5):
    """Get stories from the same category"""
    return Story.objects.filter(category=category, status='published').order_by('-created_at')[:limit]

@register.simple_tag
def get_trending_stories(days=7, limit=5):
    """Get trending stories based on views and likes in the last X days"""
    from django.utils import timezone
    import datetime
    
    date_threshold = timezone.now() - datetime.timedelta(days=days)
    
    # Get stories with the most views and likes in the last X days
    trending_stories = Story.objects.filter(
        is_draft=False,  # 只显示非草稿状态的故事
        created_at__gte=date_threshold
    ).order_by('-views', '-likes')[:limit]
    
    # 如果最近时间范围内没有足够的故事，则获取所有非草稿故事
    if len(trending_stories) < limit:
        trending_stories = Story.objects.filter(
            is_draft=False
        ).order_by('-views', '-likes')[:limit]
    
    return trending_stories 